package com.activity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.impl.client.DefaultHttpClient;

import com.model.LeaveModel;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.MenuInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.Toast;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;

public class AndroidLeaveApplicationActivity extends Activity implements
		OnItemClickListener, OnItemSelectedListener {
	Button button;
	ListView listview;
	String[] arr;
	BufferedReader rd;
	StringBuilder b;
	ArrayList<LeaveModel> arrlst;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		Spinner spinner = (Spinner) findViewById(R.id.spinner1);
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.status_array,
				android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);
		spinner.setOnItemSelectedListener(this);

		try {
			refresh();
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void refresh() throws URISyntaxException, ClientProtocolException, IOException{
		URI uri = URIUtils.createURI("http", "10.10.2.114", 8080,
				"/LeaveApplicationProcessingSystem/ViewLeaveServlet",
				"android=true", null);
		HttpGet httpget = new HttpGet(uri);
		HttpResponse response = new DefaultHttpClient().execute(httpget);
		InputStream inp = response.getEntity().getContent();
		rd = new BufferedReader(new InputStreamReader(inp));
		doProcess();
		ShowList(arrlst);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.leavemenu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.refresh:
			try {
				int previousTotalLeave = arrlst.size();
				refresh();
				int currentTotalLeave = arrlst.size();
				String message = "";
				if (previousTotalLeave == currentTotalLeave){
					message = "No leave is added";
				}
				else if (currentTotalLeave > previousTotalLeave){
					if (currentTotalLeave - previousTotalLeave < 2){
						message = "1 leave is added";
					}
					else{
						message = (currentTotalLeave - previousTotalLeave) + " leaves are added";
					}
				}
				if (!message.isEmpty()){
					Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
					Spinner spinner = (Spinner) findViewById(R.id.spinner1);
					//spinner.setSelection(0);
					ShowList(getDataWithStatus(spinner.getSelectedItem().toString()));
				}
			} catch (URISyntaxException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}

	}

	public void doProcess() throws IOException {
		arrlst = new ArrayList<LeaveModel>();
		String line;
		int i = 0;
		while ((line = rd.readLine()) != null) {
			i = 0;
			arr = line.split(";");

			if (arr.length > 1) {
				String id = arr[i].substring(arr[i].indexOf(":") + 1).trim();
				String username = arr[++i].substring(arr[i].indexOf(":") + 1)
						.trim();
				String Leavetypename = arr[++i].substring(
						arr[i].indexOf(":") + 1).trim();
				String natureofleave = arr[++i].substring(
						arr[i].indexOf(":") + 1).trim();
				String startdate = arr[++i].substring(arr[i].indexOf(":") + 1)
						.trim();
				String enddate = arr[++i].substring(arr[i].indexOf(":") + 1)
						.trim();
				String reason = arr[++i].substring(arr[i].indexOf(":") + 1)
						.trim();
				String comment = arr[++i].substring(arr[i].indexOf(":") + 1)
						.trim();
				int totalDay = Integer.parseInt(arr[++i].substring(
						arr[i].indexOf(":") + 1).trim());
				String status = arr[++i].substring(arr[i].indexOf(":") + 1)
						.trim();

				LeaveModel leaveModel = new LeaveModel(id, username,
						Leavetypename, natureofleave, startdate, enddate,
						reason, comment, totalDay, status);

				arrlst.add(leaveModel);
			}
		}
	}

	public void ShowList(ArrayList<LeaveModel> arrlst) {

		listview = (ListView) findViewById(R.id.listView1);
		listview.setAdapter(new SimpleAdapter(this, arrlst, R.layout.row,
				new String[] { "username", "leavetypename", "startdate",
						"enddate", "status" }, new int[] { R.id.textView1,
						R.id.textView2, R.id.textView3, R.id.textView4,
						R.id.textView5 }));
		listview.setOnItemClickListener(this);

		TextView textNoRecord = (TextView) findViewById(R.id.textnorecord);
		if (arrlst.size() == 0) {
			textNoRecord.setVisibility(TextView.VISIBLE);
			textNoRecord.setHeight(40);
		} else {
			textNoRecord.setVisibility(TextView.INVISIBLE);
			textNoRecord.setHeight(0);
		}
	}

	public void onItemClick(AdapterView<?> av, View v, int position, long id) {
		// TODO Auto-generated method stub
		Intent i = new Intent(this, LeaveDetailActivity.class);
		i.putExtra("detail",
				((LeaveModel) av.getAdapter().getItem(position)).toDetail());
		startActivity(i);
		v.setBackgroundColor(Color.rgb(100, 100, 100));
	}

	public void onItemSelected(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		// TODO Auto-generated method stub
		ShowList(getDataWithStatus(arg0.getItemAtPosition(position).toString()));
	}

	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub

	}

	private ArrayList<LeaveModel> getDataWithStatus(String status) {
		ArrayList<LeaveModel> result = new ArrayList<LeaveModel>();

		if (status.equalsIgnoreCase("all")) {
			result = arrlst;
		} else {
			for (LeaveModel leaveModel : arrlst) {
				if (leaveModel.get("status").toLowerCase()
						.indexOf(status.toLowerCase()) > -1) {
					result.add(leaveModel);
				}
			}
		}

		return result;
	}
}
